<!--
 * @Description:
 * @Author: zhaolei
 * @Date: 2023-04-12 16:37:21
-->
<template>
  <avue-form
    ref="addForm"
    v-model="form"
    v-loading="loading"
    :option="tableOption"
    :upload-exceed="uploadExceed"
    :upload-error="uploadError"
    :upload-change="$uploadChange"
  >
    <template
      v-if="action === 'view'"
      #nickName
    >
      <span>{{ form.nickName }}</span>
      <span
        v-if="form.formerName"
        style="font-weight: 600; margin-left: 5px"
      >
        (曾用名:{{ form.formerName }})
      </span>
    </template>
    <template #medicalHistory>
      <div v-if="action === 'view'">{{ form.medicalHistory }}</div>
      <div v-else>
        <el-input
          v-model="form.medicalHistory"
          maxlength="200"
          placeholder="请输入病史"
        ></el-input>
      </div>
    </template>
    <template #adoptionSource>
      <div v-if="action === 'add'">
        <el-select v-model="form.adoptionSource">
          <el-option
            v-for="item in list"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div v-else-if="action === 'edit'">
        <span>
          <el-select
            v-model="form.adoptionSource"
            :disabled="form.adoptionSource === '2' && action === 'edit'"
          >
            <span
              v-for="item in ADOPTION_SOURCE_List"
              :key="item.key"
            >
              <el-option
                :key="item.value"
                :label="item.label"
                :disabled="action === 'edit' && item.value === '2'"
                :value="item.value"
              ></el-option>
            </span>
          </el-select>
        </span>
      </div>
      <div v-else>
        {{ form.adoptionSource | adoptFilters }}
      </div>
    </template>
    <template #givenName>
      <el-select
        v-model="form.givenName"
        filterable
        clearable
        remote
        :disabled="
          (form.adoptionSource === '2' && action === 'edit') ||
          action === 'view'
        "
        placeholder="请选择送养人"
        :remote-method="remoteMethod"
      >
        <el-option
          v-for="item in phoneList"
          :key="item.userId"
          :label="item.phone"
          :value="item.userId"
        >
          <template>
            <div
              class="sb"
              style="padding: 0 20px"
            >
              <span>{{ item.nickname }}</span>
              <span>{{ item.phone }}</span>
            </div>
          </template>
        </el-option>
      </el-select>
    </template>
    <!-- <template #ageGroup="{disabled}">
      <el-select
        v-model="form.ageGroup"
        clearable
        :disabled="disabled"
        placeholder="请选择年龄段"
      >
        <el-option
          v-for="item in ageGroupList"
          :key="item.attributeCode"
          :label="item.attributeName"
          :value="item.attributeCode"
        >
        </el-option>
      </el-select>
    </template> -->
    <template #bodilyForm="{ disabled }">
      <el-select
        v-model="form.bodilyForm"
        clearable
        :disabled="disabled"
        placeholder="请选择体型"
      >
        <el-option
          v-for="item in bodilyFormList"
          :key="item.attributeCode"
          :label="item.attributeName"
          :value="item.attributeCode"
        ></el-option>
      </el-select>
    </template>
    <template #furColor="{ disabled }">
      <el-select
        v-model="form.furColor"
        clearable
        :disabled="disabled"
        placeholder="请选择毛色"
      >
        <el-option
          v-for="item in furColorList"
          :key="item.attributeCode"
          :label="item.attributeName"
          :value="item.attributeCode"
        ></el-option>
      </el-select>
    </template>
    <template #hairLength="{ disabled }">
      <el-select
        v-model="form.hairLength"
        clearable
        :disabled="disabled"
        placeholder="请选择毛发长度"
      >
        <el-option
          v-for="item in hairLengthList"
          :key="item.attributeCode"
          :label="item.attributeName"
          :value="item.attributeCode"
        ></el-option>
      </el-select>
    </template>
    <!-- 3todo -->
    <template #sick="{ disabled }">
      <div style="display: flex">
        <el-select
          v-model="form.sick"
          :disabled="disabled"
          style="width: 20% !important"
        >
          <span
            v-for="item in IF_ILL_LIST"
            :key="item.key"
          >
            <el-option
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </span>
        </el-select>
        <el-input
          v-model="form.medicalHistory"
          style="width: 80%; margin-left: 20px"
          maxlength="50"
          placeholder="可备注曾患病症"
        ></el-input>
      </div>
    </template>
    <template #birthDay="{ disabled }">
      <div class="flex">
        <el-date-picker
          v-if="!isUnknownTime"
          v-model="form.birthDay"
          type="date"
          :disabled="disabled"
          :picker-options="pickerOptions"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :editable="false"
          placeholder="请选择 出生日期"
          style="flex: 1; margin-right: 10px"
        ></el-date-picker>
        <el-checkbox
          v-if="isUnknownTime || action === 'add' || action === 'edit'"
          v-model="isUnknownTime"
          :disabled="disabled"
        >
          未知
        </el-checkbox>
      </div>
    </template>
    <!-- <template #topTime>
      <span>{{ form.topStartTime }} - {{ form.topEndTime }}</span>
    </template> -->
  </avue-form>
</template>

<script>
import { tableOption } from '@/const/crud/pet/commonForm';
import { fetchBaseList } from '@/api/core/base';
import { getObj } from '@/api/core/pet-file';
import { getListByTwoCode } from '@/api/core/classify';
import { getPhoneList } from '@/api/core/agreement';
import { ADOPTION_SOURCE_List, IF_ILL_LIST } from '@/const/type';
export default {
  name: '',
  filters: {
    adoptFilters(val) {
      if (val === '1') {
        return '基地救助';
      } else if (val === '2') {
        return '个人送养';
      } else if (val === '3') {
        return '个人救助';
      } else {
        return '其他';
      }
    },
  },
  props: {
    action: {
      type: String,
      default: 'add',
    },
    id: {
      type: [Object, String],
    },
    page: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      dataObj: {},
      form: {
        isUnknownTime: false,
      },
      ADOPTION_SOURCE_List,
      IF_ILL_LIST,
      list: [
        {
          // label: '基地搜捕',
          label: '基地救助',
          value: '1',
        },
        {
          label: '个人救助',
          value: '3',
        },
        {
          label: '其他',
          value: '9',
        },
      ],
      treeData: [],
      loading: false,
      // ageGroupList: [],
      personalityList: [],
      bodilyFormList: [],
      furColorList: [],
      hairLengthList: [],
      phoneList: [],
      isUnknownTime: false,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  computed: {
    tableOption() {
      return tableOption(this.action === 'view', this.page);
    },
  },
  watch: {
    isUnknownTime(val) {
      console.log('vvv', val);
      this.form.isUnknownTime = val;
      if (val) {
        this.form.birthDay = '00-00-00'; // 避过校验,传给接口改为空字符串
      } else {
        this.form.birthDay = '';
      }
    },
    'form.baseId': {
      immediate: true,
      async handler(val, oldVal) {
        if (val !== oldVal && val) {
          await this.init();
          const obj = this.treeData.find((el) => el.id === val);
          this.form.baseAddress = obj && obj.address;
        }
      },
    },
    'form.adoptionSource': {
      immediate: true,
      async handler(val, oldVal) {
        if (val !== '2') {
          this.form.phone = '';
        }
      },
    },
    'form.petType': {
      immediate: true,
      async handler(val, oldVal) {
        const arr = [
          // 'ageGroup',
          // 'personality',
          'bodilyForm',
          'furColor',
          'hairLength',
        ];
        if (val && val[0]) {
          arr.forEach((el) => {
            this.getListByTwoCode(val[0], el);
          });
        }
        if (this.validatenull(val)) {
          arr.forEach((el) => {
            this[`${el}List`] = [];
            this.form[el] = '';
          });
        }
        if (oldVal && oldVal[0] && val && val[0] && val[0] !== oldVal[0]) {
          arr.forEach((el) => {
            this.form[el] = '';
          });
        }
      },
    },
  },
  mounted() {
    this.id && this.getDetail();
    this.getUserPhoneList();
  },
  methods: {
    sourceChange(val) {
      // console.log('vvv', val);
      // if (val !== '2') {
      //   this.ADOPTION_SOURCE_List[1].display = true;
      // }
    },
    remoteMethod(phone) {
      if (phone !== '' && phone.length > 1) {
        setTimeout(() => {
          this.getUserPhoneList({ phone });
        }, 50);
      } else {
        this.phoneList = [];
      }
    },
    async getUserPhoneList(params) {
      this.phoneList = [];
      const res = await getPhoneList(params);
      this.phoneList = res.data.data;
    },
    async getListByTwoCode(typeCode, attributeCode) {
      const res = await getListByTwoCode(typeCode, attributeCode);
      this[`${attributeCode}List`] = res.data.data;
    },
    async getDetail() {
      try {
        this.loading = true;
        const res = await getObj(this.id);
        const dataObj = { ...res.data.data };
        this.$emit('selectChange', dataObj);
        this.form = { ...dataObj };
        this.loading = false;
        // this.form.avatar = JSON.parse(dataObj.avatar)[0].url;

        this.form.petType = [dataObj.typeCode, dataObj.varietyCode];
        this.form.$petType = [dataObj.typeName, dataObj.varietyName];
        // if (this.validatenull(JSON.parse(dataObj.personality))) {
        //   this.form.personality = [];
        // } else {
        //   this.form = {
        //     ...this.form,
        //     ...this.transform(
        //       [
        //         // 'ageGroup',
        //         'personality',
        //         // 'bodilyForm',
        //         // 'furColor',
        //         // 'hairLength',
        //       ],
        //       dataObj
        //     ),
        //   };
        // }
        this.form.isUnknownTime = !this.form.birthDay;
        this.isUnknownTime = !this.form.birthDay;
      } catch (error) {
        this.loading = false;
      }

      console.log('this.form', this.form);
    },
    transform(arr, target) {
      const obj = {};
      arr.forEach((el) => {
        const temp = JSON.parse(target[el]);
        if (temp.length > 1) {
          obj[el] = [];
          temp.forEach((v) => {
            obj[el].push(v.code);
          });
        } else {
          obj[el] = [temp[0].code];
        }
      });
      return obj;
    },
    async init() {
      const res = await fetchBaseList();
      this.treeData = res.data.data;
    },
    uploadExceed(limit, files, fileList, column) {
      console.log(limit, files, fileList, column);
      this.$message.error(`只能上传${limit}个文件`);
    },
    uploadError(error, column) {
      if (error === '文件太大不符合') {
        this.$message.warning(`文件大小不能超过${column.fileSize / 1024}M`);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.hidden-options {
  display: none;
}
.display-options {
  display: true;
}
</style>
